//
//  SecondViewController.m
//  Client
//
//  Created by 顾悦 on 16/3/21.
//
//

#import "MyOrdersViewController.h"
#import "ThemeColor.h"
#import "BulkOrderViewController.h"
#import "GroupOrderCell.h"
#import "ThemeColor.h"

#import "GroupOrderService.h"
#import "GroupOrder.h"
#import "SVPullToRefresh.h"

static NSString * HTMLURL = @"order/orderList.html";
static NSString * bulkHTMLURL = @"order/aBulkOrder.html";





@interface MyOrdersViewController () <UITableViewDelegate, UITableViewDataSource>
{

    UIView *bgView;
    UIView *lineLabel;


}
@property (nonatomic, strong) UIButton *lastBtn;
@property (nonatomic, strong) UIControl *lastControl;

@property (nonatomic, strong) UITableView *tableView;


@property (nonatomic, strong) GroupOrderService *groupOrderService;
@property (nonatomic, strong) NSString *orderType;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNo;
@property (strong, nonatomic) NSArray<GroupOrder *> *items;


@end

@implementation MyOrdersViewController

-(GroupOrderService *)groupOrderService{
    if (!_groupOrderService) {
        _groupOrderService = GroupOrderService.new;
    }
    return _groupOrderService;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.title = @"我的订单";
    
    self.HTMLURL = HTMLURL;
    self.view.backgroundColor = [UIColor blueColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payFinished:) name:@"NotificationNamePayFinished" object:nil];

    self.pageSize = 10;
    self.pageNo = 1;
    self.orderType = @"1";
    
//    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithCustomView:button];
//    self.navigationItem.rightBarButtonItem = btn;
    
    

    [self setUpTitileView];
    
    /* 原生的改成调用h5
    [self setUpSegment];
    
    _tableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        tableView.frame = CGRectMake(0, bgView.bottom, ScreenWidth, ScreenHeight-49-40-64);
        tableView.backgroundColor = [UIColor colorWithHex:@"#f7f8f9"];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tableView registerClass:[GroupOrderCell class] forCellReuseIdentifier:@"GroupOrderCell"];
        [self.view addSubview:tableView];
        tableView;
    });
    _tableView.hidden = YES;
    bgView.hidden = YES;
     
     */
   
    
}


-(void)setUpTitileView{

    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(self.view.width/2-150, 0, 160, 35)];
    titleView.layer.borderColor = [UIColor whiteColor].CGColor;
    titleView.layer.borderWidth = 1;
    titleView.layer.cornerRadius = 5;
    titleView.clipsToBounds = YES;
    self.navigationItem.titleView = titleView;
    
    
    UIButton *orderBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    orderBtn.frame = CGRectMake(0, 0, titleView.width/2, titleView.height);
    [orderBtn setTitleColor:[ThemeColor orangeColor] forState:UIControlStateNormal];
//    [orderBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    orderBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [orderBtn setTitle:@"我的订单" forState:UIControlStateNormal];
    orderBtn.backgroundColor = [UIColor whiteColor];
//    orderBtn.backgroundColor = [ThemeColor orangeColor];
    [orderBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:orderBtn];
    self.lastBtn = orderBtn;
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(orderBtn.right, 0, 80, titleView.height);
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    [button setTitle:@"团购订单" forState:UIControlStateNormal];
    button.backgroundColor = [ThemeColor orangeColor];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:button];

}

//
-(void)setUpSegment{
    
    NSArray *array = @[@"可用团购",@"待服务",@"团购明细"];
    bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    
    for (int i = 0 ; i<array.count; i++) {
        
        NSString *contentStr = array[i];
        float width = ScreenWidth/array.count;
        CGSize contentSize = [contentStr sizeWithFont:[UIFont systemFontOfSize:14] maxSize:CGSizeMake(200, 40)];
        UIControl *control = [[UIControl alloc]init];
        [control addTarget:self action:@selector(controlEvent:) forControlEvents:UIControlEventTouchUpInside];
        control.frame = CGRectMake(width * i, 0, width, 38);
        control.tag = 3333+i;
        [bgView addSubview:control];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake((width-contentSize.width-30)/2, 9, contentSize.width, 20)];
        titleLabel.font = Font(14);
        titleLabel.text = array[i];
        titleLabel.tag = 111;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        [control addSubview:titleLabel];
        
        UILabel *numLabel = [[UILabel alloc]initWithFrame:CGRectMake(titleLabel.right+5, 9, 20, 20)];
        numLabel.layer.cornerRadius = 10;
        numLabel.clipsToBounds = YES;
        numLabel.text = @"20";
        numLabel.backgroundColor = [ThemeColor orangeColor];
        numLabel.font = Font(12);
        numLabel.textAlignment = NSTextAlignmentCenter;
        numLabel.textColor = [UIColor whiteColor];
        numLabel.tag = 222;
        [control addSubview:numLabel];
        
        
        
        
        
        if (i == 0) {
            lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(control.x, control.bottom, width, 2)];
            lineLabel.backgroundColor = [ThemeColor orangeColor];
            [bgView addSubview:lineLabel];
            self.lastControl = control;

        }
    }
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, lineLabel.bottom, ScreenWidth, 10)];
    label.backgroundColor = [ThemeColor lightGrayBGColor];
    [bgView addSubview:label];

    
    
}


//   替换成调用H5  此方法废弃------
-(void)controlEvent:(UIControl *)sender{
    
    UILabel *label = [(UILabel *)sender viewWithTag:111];
    if ([label.text isEqualToString:@"可用团购"]) {
        self.orderType = @"1";
    }else if ([label.text isEqualToString:@"待服务"]){
        self.orderType = @"2";
    }else if ([label.text isEqualToString:@"团购明细"]){
        self.orderType = @"3";
    }
    
    
    [UIView animateWithDuration:0.1 animations:^{
        lineLabel.frame = CGRectMake(sender.x, sender.bottom, sender.width, 2);
        
    } completion:nil];
    
    [self getGroupBuyOrderList:NO];

    
    
}

-(void)buttonClick:(UIButton *)sender{

    [_lastBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _lastBtn.backgroundColor = [ThemeColor orangeColor];
    
    [sender setTitleColor:[ThemeColor orangeColor] forState:UIControlStateNormal];
    sender.backgroundColor = [UIColor whiteColor];
    self.lastBtn = sender;
    
    bgView.hidden = YES;
    self.tableView.hidden = YES;

    self.HTMLURL = [sender.titleLabel.text isEqualToString:@"我的订单"] ? HTMLURL : bulkHTMLURL;
    [super viewDidAppear:YES];

//    if ([sender.titleLabel.text isEqualToString:@"我的订单"]) {
//        self.HTMLURL = HTMLURL;
//        self.tableView.hidden = YES;
//        bgView.hidden = YES;
//        
//    }else{
//        self.HTMLURL = nil;
//        self.tableView.hidden = NO;
//        bgView.hidden = NO;
//        //请求
//        [self getGroupBuyOrderList:NO];
//        [self setupInfiniteScrolling];
//        
//    }
    

}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{


    return _items.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    GroupOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GroupOrderCell"];
//    DrawBillModel *info =_sourceArray[indexPath.row];
//    [cell setDrawBillInfo:info];
    cell.orderBtn.tag = 222+indexPath.section;
    
    GroupOrder *p = self.items[indexPath.section];
    [cell fillData:p orderType:[self.orderType integerValue]];
    
    
    cell.orderDetailBlock = ^(NSString *str, NSInteger tag) {
        
        GroupOrder *model = self.items[tag - 222];

        if ([str isEqualToString:@"预约服务"]) {
            
            ClientWebViewController *webViewController = ClientWebViewController.new;
            webViewController.HTMLURL = [NSString stringWithFormat:@"../groupbuy/groupAppointment.html?Id=%@&ServiceCat1Id=%@&GroupBuyingCommunitiesDetailId=%@&Sqlnum=%ld&CommunityId=%@", model.orderId,model.serviceCat1Id,model.groupBuyingCommunitiesDetailId,model.sqlnum,model.communityId];
            webViewController.title = @"预约服务";
            [self.navigationController pushViewController:webViewController animated:YES];
        }
    };
    
    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    GroupOrder *model = self.items[indexPath.section];

    NSString *urlStr = [self.orderType integerValue] == 2 ? [NSString stringWithFormat:@"../order/order_details.html?orderId=%@", model.orderId]: [NSString stringWithFormat:@"../groupbuy/groupOrderDetail.html?orderid=%@", model.orderId];
    ClientWebViewController *webViewController = ClientWebViewController.new;
    webViewController.HTMLURL = urlStr;
    webViewController.title = @"订单详情";
    [self.navigationController pushViewController:webViewController animated:YES];
    
   
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return [GroupOrderCell cellHeight];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{


    return 0.0001;
}


//进入团购订单
- (void)goToGroup
{
    BulkOrderViewController *vc = [[BulkOrderViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NotificationNamePayFinished" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -

- (void)payFinished:(NSNotification *)notification {
    if (self.tabBarController.selectedIndex != 1) {
        return;
    }
    ClientWebViewController *webViewController = ClientWebViewController.new;
    webViewController.hidesBottomBarWhenPushed = YES;
    NSNumber *userInfo = notification.object;
    if (!userInfo) {
        webViewController.HTMLURL = @"payment/finish.html";
    } else if ([userInfo respondsToSelector:@selector(boolValue)] && ![userInfo boolValue]) {
        webViewController.HTMLURL = @"payment/fail.html";
    }
    [self.navigationController pushViewController:webViewController animated:YES];
}



- (void)setupInfiniteScrolling {
    
    __weak typeof(self) weakSelf = self;
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf loadMoreInfos];
    }];
}

- (void)loadMoreInfos {
    [self getGroupBuyOrderList:YES];
}

//团购订单列表的请求
-(void)getGroupBuyOrderList:(BOOL)flag {
    if (!flag) {
        self.pageNo = 1;
    }
    [LoadingView show];
    [self.groupOrderService GetGrouponOrdersType:self.orderType PageSize:@(self.pageSize) PageNo:@(self.pageNo) completionHanlder:^(NSDictionary *items, NSError *error) {
        [LoadingView dismiss];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.infiniteScrollingView stopAnimating];
        });
        if (error) {
            [LoadingView showToast:[error localizedDescription]];
        } else {
                        
            NSMutableArray<GroupOrder *> *ps = NSMutableArray.new;
            NSArray *itemArray = items[@"LstOrderS"];
            for (NSDictionary *i in itemArray) {
               
              [ps addObject:[[GroupOrder alloc] initWithDictionary:i]];
            }
            if (flag) {
                self.items = [[self.items arrayByAddingObjectsFromArray:ps] mutableCopy];
            } else {
                self.items = ps;
            }
            self.pageNo ++;
        }
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            
            UIControl *control = [bgView viewWithTag:3333];
            [self changeFrame:control number:[items[@"UseCount"] intValue]];

            UIControl *control1 = [bgView viewWithTag:3334];
            [self changeFrame:control1 number:[items[@"ServicIngCount"] intValue]];


            UIControl *control2 = [bgView viewWithTag:3335];
            [self changeFrame:control2 number:[items[@"DetailCount"] intValue]];

            
        });
        
        
    }];

    
}

-(void)changeFrame:(UIControl *)sender number:(int)num{

    UILabel *label1 = [sender viewWithTag:222];
    UILabel *labellabel1 = [sender viewWithTag:111];
    label1.text =  [NSString stringWithFormat:@"%d",num];
    label1.width = num == 0 ? 0 : 20;
    labellabel1.x = num == 0 ? (ScreenWidth/3-labellabel1.width)/2 : (ScreenWidth/3-labellabel1.width-30)/2;
}

@end
